var express = require('express');
var router = express.Router();
const order = require("../sql/Order");
const getMonthDate = require("./untils/getMonthDate");

const getDashboardData = require("./untils/getDashboardData")

const ws = require('express-ws')
ws(router);

let m;
const wss = [];
router.ws("/",(ws,req)=>{
  wss.push(ws);
  ws.on("message", (msg) => {
    order.find().then(async oData=>{
      
      const date = getMonthDate(m);

      const s = new Date(date[0]);
      const e = new Date(date[1]);
      const orderData = oData.filter(val=>{
        const n = new Date(val.OrderDate).getTime();
        return n >= s.getTime() && n <= e.getTime();
      })

      const uData = await getDashboardData(orderData);
      // 给所有的客户端广播消息
      wss.forEach((e) => {
        e.send(JSON.stringify(uData));
      })
    }).catch(code=>{
      console.error(code);
      res.send( code );
    })

  })
  // close 事件表示客户端断开连接时执行的回调函数
  ws.on('close', function (e) {
    console.log('close connection')
  })
})

// 打开页面
router.get('/', function(req, res, next) {
  res.render('dashboard');
});

// 获取数据
router.get("/getData", (req,res,next)=>{
  m = req.query.month;
  const date = getMonthDate( m );
  order.find().then(async oData=>{
    const s = new Date(date[0]);
    const e = new Date(date[1]);
    const orderData = oData.filter(val=>{
      const n = new Date(val.OrderDate).getTime();
      return n >= s.getTime() && n <= e.getTime();
    })
    const uData = await getDashboardData(orderData);
    res.send( uData );
  }).catch(code=>{
    console.error(code);
    res.send( code );
  })
})

module.exports = router;